package com.ruoyi.web.controller.shop.goods;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Buffet;
import com.ruoyi.common.core.domain.entity.BuffetDetail;
import com.ruoyi.common.core.domain.entity.BuffetExamine;
import com.ruoyi.common.core.domain.entity.BuffetExamineDetail;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TimeUtils;
import com.ruoyi.system.mapper.BuffetDetailMapper;
import com.ruoyi.system.service.ApproveService;
import com.ruoyi.system.service.BuffetExamineDetailService;
import com.ruoyi.system.service.BuffetExamineService;
import com.ruoyi.system.service.BuffetService;
import com.ruoyi.system.service.req.BuffetDTO;
import com.ruoyi.system.service.resp.BuffetExamineDetailDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/2
 **/
@Api("自助餐菜单")
@RestController
@RequestMapping("/shop/buffet")
public class BuffetController extends BaseController {
    @Resource
    private BuffetService buffetService;

    @Resource
    private BuffetExamineService buffetExamineService;

    @Resource
    private BuffetExamineDetailService buffetExamineDetailService;

    @Resource
    private ApproveService approveService;

    @Resource
    private BuffetDetailMapper buffetDetailMapper;

    @ApiOperation("分页获取自助餐菜单")
    @GetMapping("/list")
    public TableDataInfo list(Buffet buffet) {
        startPage();
        List<Buffet> buffets = buffetService.selectList(buffet);
        return getDataTable(fillToDTO(buffets));
    }

    @ApiOperation("获取自助餐菜单")
    @GetMapping("/listAll")
    public TableDataInfo listAll(Buffet buffet) {
        List<Buffet> buffets = buffetService.selectList(buffet);
        return getDataTable(buffets);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(buffetService.selectById(id));
    }

    @PostMapping("/deduplicate")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deduplicate(@Validated @RequestBody Buffet buffet) {
        Buffet query = new Buffet();
        query.setType(buffet.getType());
        query.setCreateTime(TimeUtils.getTodayBegin());
        List<Buffet> buffets = buffetService.selectList(query);
        if (!CollectionUtils.isEmpty(buffets)) {
//            return error("每天的自助餐" + buffet.getType() + "菜单只能有一个");
        }
        Buffet buffetSource = buffetService.selectById(buffet.getId());
        if (buffetSource == null) {
            logger.warn("业务错误 复制自助餐菜单 没找到原来的 {}", JSON.toJSONString(buffet));
            return error("没找到这个自助餐菜单");
        }
        Long sourceId = buffetSource.getId();
        buffetSource.setCreateBy(SecurityUtils.getNickName());
        buffetSource.setId(null);
        Boolean result = buffetService.create(buffetSource);
        if (!result) {
            return error();
        }
        List<BuffetDetail> sourceDetails = buffetDetailMapper.selectList(BuffetDetail.builder()
                .buffetId(sourceId).build());
        if (CollectionUtils.isEmpty(sourceDetails)) {
            return success();
        }
        sourceDetails.forEach(s -> {
            s.setBuffetId(buffetSource.getId());
            buffetDetailMapper.insert(s);
        });
        createIfNoBuffetExamine(buffet.getId());
        return success();
    }

    @Log(title = "添加自助菜单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody Buffet buffet) {
        String area = SecurityUtils.getUserLocation();
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("园区为全部的用户无法下单");
        }

        Buffet query = new Buffet();
        query.setType(buffet.getType());
        query.setCreateTime(TimeUtils.getTodayBegin());
        List<Buffet> buffets = buffetService.selectList(query);
        if (!CollectionUtils.isEmpty(buffets)) {
//            return error("每天的自助餐" + buffet.getType() + "菜单只能有一个");
        }
        buffet.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = buffetService.create(buffet);
        if (!result) {
            return error();
        }
        createIfNoBuffetExamine(buffet.getId());
        return success();
    }

    private void createIfNoBuffetExamine(Long buffetId) {
        if (buffetId == null) {
            return;
        }
        List<BuffetExamine> buffetExamines = buffetExamineService.selectList(BuffetExamine.builder().buffetId(buffetId).build());
        if (CollectionUtils.isEmpty(buffetExamines)) {
            BuffetExamine buffetExamine = new BuffetExamine();
            buffetExamine.setBuffetId(buffetId);
            buffetExamine.setStatus("质检中");
            buffetExamine.setArea("一区");
            buffetExamine.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            buffetExamineService.create(buffetExamine);

            BuffetExamine buffetExamine1 = new BuffetExamine();
            buffetExamine1.setBuffetId(buffetId);
            buffetExamine1.setStatus("质检中");
            buffetExamine1.setArea("二区");
            buffetExamine1.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            buffetExamineService.create(buffetExamine1);
        }
    }

    @Log(title = "修改自助菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody Buffet buffet) {
        buffet.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        if ("启用".equals(buffet.getStatus())) {
            Buffet buffet1 = buffetService.selectById(buffet.getId());
            List<Buffet> buffets = buffetService.selectQiyongList(buffet1.getType(), buffet1.getId());
            if (!CollectionUtils.isEmpty(buffets) && buffets.size() > 0) {
                return AjaxResult.error("早餐/中餐类型的菜单只能同时启动一个，请先关闭原有生效的菜单");
            }
        }
        Boolean result = buffetService.update(buffet);
        if (!result) {
            return error();
        }
        createIfNoBuffetExamine(buffet.getId());
        return success();
    }

    @Log(title = "删除自助菜单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long id) {
        Boolean result = buffetService.deleteById(id);
        //同时删除质检单
        BuffetExamine buffetExamine = new BuffetExamine();
        buffetExamine.setBuffetId(id);
        List<BuffetExamine> list = buffetExamineService.selectList(buffetExamine);
        for (BuffetExamine examine : list) {
            buffetExamineService.deleteById(examine.getId());

            BuffetExamineDetail examineDetail = new BuffetExamineDetail();
            examineDetail.setExamineId(examine.getId());
            List<BuffetExamineDetail> details = buffetExamineDetailService.selectList(examineDetail);
            for (BuffetExamineDetail detail : details) {
                buffetExamineDetailService.deleteById(detail.getId());
            }
        }
        if (result) {
            return success();
        }
        return error();
    }

    private List<BuffetDTO> fillToDTO(List<Buffet> buffets) {
        if (CollectionUtils.isEmpty(buffets)) {
            return Collections.emptyList();
        }
        List<BuffetDTO> buffetDTOS = buffets.stream().filter(Objects::nonNull).map(b -> {
            BuffetDTO buffetDTO = new BuffetDTO();
            buffetDTO.setId(b.getId());
            buffetDTO.setType(b.getType());
            buffetDTO.setName(b.getName());
            buffetDTO.setPrice(b.getPrice());
            buffetDTO.setStatus(b.getStatus());
            buffetDTO.setCreateBy(b.getCreateBy());
            buffetDTO.setCreateTime(b.getCreateTime());
            buffetDTO.setUpdateBy(b.getUpdateBy());
            buffetDTO.setUpdateTime(b.getUpdateTime());
            buffetDTO.setRemark(b.getRemark());

//            ApproveMission approveMission = approveService.getApproveMissionByActivityd(b.getId(), "自助餐菜单详情审批");
//            if (approveMission == null) {
//                buffetDTO.setApproveStatus("未提交审批");
//            } else {
//                buffetDTO.setApproveStatus(approveMission.getStatus());
//                buffetDTO.setApproveMissionId(approveMission.getId());
//            }
            List<BuffetExamine> buffetExamines = buffetExamineService.selectList(BuffetExamine.builder()
                    .buffetId(b.getId()).build());
            if (CollectionUtils.isEmpty(buffetExamines)) {
                buffetDTO.setExamineStatus("未提交质检");
            } else {
                buffetExamines.forEach(i -> {
                    if(Objects.equals(i.getArea(), "一区")){
                        buffetDTO.setExamineStatus(i.getStatus());
                        buffetDTO.setExamineId(i.getId());
                    }else if(Objects.equals(i.getArea(), "二区")){
                        buffetDTO.setExamineStatusTwo(i.getStatus());
                        buffetDTO.setExamineIdTwo(i.getId());
                    }
                });
//                buffetDTO.setExamineStatus(buffetExamines.get(0).getStatus());
//                buffetDTO.setExamineId(buffetExamines.get(0).getId());
            }
            return buffetDTO;
        }).collect(Collectors.toList());
        PageInfo<Buffet> oldPage = new PageInfo<>(buffets);
        Page<BuffetDTO> newPage = new Page<>();
        newPage.addAll(buffetDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }
}
